<template>
  <div class="container">
    <div class="app-container">
      <!-- 组织架构 -->
      <!-- 展示树形结构 -->
      <el-tree
        :data="depts"
        :expand-on-click-node="false"
        :props="defaultProps"
        default-expand-all
      >
        <!-- 节点结构 -->
        <!-- v-slot="{node,data}" 只能作用在 template标签中-->
        <!-- 可以简写为 #default -->
        <template v-slot:default="{ data }">
          <el-row
            type="flex"
            justify="space-between"
            style="width: 100%; height: 40px"
            align="middle"
          >
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4" class="tree-manager-box">
              <span>{{ data.managerName }}</span>
              <el-dropdown>
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    @click.native="showAddDialog('新增部门', data.id)"
                    >添加子部门</el-dropdown-item
                  >
                  <el-dropdown-item
                    @click.native="showEditDialog('编辑部门', data)"
                    >编辑部门</el-dropdown-item
                  >
                  <el-dropdown-item @click.native="deleteDepartment(data.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown></el-col
            >
          </el-row>
        </template>
      </el-tree>
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="40%"
        @close="cancelDialog"
      >
        <el-form
          ref="deptForm"
          :model="new_dept"
          label-width="100px"
          size="small"
          :rules="deptRules"
        >
          <el-form-item label="部门名称" prop="name"
            ><el-input
              placeholder="2-10个字符"
              v-model="new_dept.name"
            ></el-input
          ></el-form-item>
          <el-form-item label="部门编码" prop="code"
            ><el-input placeholder="2-10个字符" v-model="new_dept.code">
            </el-input
          ></el-form-item>
          <el-form-item label="部门负责人" prop="managerId"
            ><el-select
              v-model="new_dept.managerId"
              placeholder="请选择负责人"
              style="width: 100%"
            >
              <el-option
                v-for="item in managers"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              >
              </el-option> </el-select
          ></el-form-item>
          <el-form-item label="部门介绍" prop="introduce"
            ><el-input
              placeholder="部门介绍 1- 100个字符"
              type="textarea"
              :rows="3"
              v-model="new_dept.introduce"
              maxlength="100"
              minlength="1"
              show-word-limit
            ></el-input
          ></el-form-item>
          <el-form-item style="padding-left: 100px">
            <el-button @click="cancelDialog">取 消</el-button>
            <el-button
              type="primary"
              @click="title === '新增部门' ? addDepartment() : editDepartment()"
              >确 定</el-button
            ></el-form-item
          >
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getDepartmentListService,
  addDepartmentService,
  editDepartmentService,
  deleteDepartmentService,
  getDeptMannagerListService,
} from "@/api/department.js";

import { transListToTreeData, parseTime } from "@/utils/index.js";

export default {
  name: "Department",
  created() {
    this.getDepartment(); //调用获取组织架构数据的方法
    this.getMannagers();
  },

  data() {
    return {
      deptList: [], //部门列表
      depts: [], //数据属性
      defaultProps: {
        label: "name", // 要显示的字段的名字
        children: "children", // 读取子节点的字段名字
      },

      managers: [], // 部门负责人列表
      title: "", // 对话框标题
      new_dept: {
        code: "",
        introduce: "",
        managerId: "",
        name: "",
        pid: "",
      },
      dialogVisible: false,
      //部门校验规则
      deptRules: {
        code: [
          { required: true, message: "请输入部门编码", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "字符长度不在2-10之间",
            trigger: "change",
          },
          {
            trigger: "blur",

            validator: (rule, value, callback) => {
              let deptList = this.deptList;
              if (this.new_dept.id) {
                deptList = this.deptList.filter(
                  (item) => item.id !== this.new_dept.id
                );
              }
              if (deptList.some((item) => item.code === value)) {
                callback(new Error("该编码已存在"));
              } else callback();
            },
          },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
        ],
        managerId: [
          {
            required: true,
            message: "请选择负责人",
            trigger: "blur",
          },
        ],
        name: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "字符长度不在2-10之间",
            trigger: "change",
          },
          {
            trigger: "blur",
            validator: (rule, value, callback) => {
              let deptList = this.deptList;
              if (this.new_dept.id) {
                deptList = this.deptList.filter(
                  (item) => item.id !== this.new_dept.id
                );
              }
              if (deptList.some((item) => item.name === value)) {
                callback(new Error("该部门名称已存在"));
              } else {
                callback();
              }
            },
          },
        ],
      },
    };
  },
  methods: {
    //封装一个调用 api 获取获取组织架构数据的方法
    async getDepartment() {
      const res = await getDepartmentListService();
      this.deptList = res.data;
      this.depts = transListToTreeData(res.data, 0);
    },
    //获取部门负责人列表
    async getMannagers() {
      const res = await getDeptMannagerListService();
      this.managers = res.data;
    },
    //显示新增对话框
    showAddDialog(title, id) {
      this.new_dept = {
        code: "",
        introduce: "",
        managerId: "",
        name: "",
        pid: "",
      };
      this.title = title;
      this.new_dept.pid = id;
      this.dialogVisible = true;
    },
    //新增部门
    addDepartment() {
      this.$refs.deptForm.validate(async (isOk) => {
        if (isOk) {
          await addDepartmentService(this.new_dept);
          this.$message.success("新增部门成功");
          //重新获取部门信息
          this.getDepartment();
          this.dialogVisible = false;
        }
      });
    },
    //取消对话框按钮
    cancelDialog() {
      this.$refs.deptForm.resetFields();
      this.dialogVisible = false;
    },
    //显示编辑对话框
    showEditDialog(title, data) {
      this.title = title;
      this.new_dept = data;
      this.dialogVisible = true;
    },
    //编辑部门
    editDepartment() {
      this.$refs.deptForm.validate(async (valid) => {
        if (valid) {
          let createTime = new Date();
          createTime = parseTime(createTime);
          this.new_dept.createTime = createTime;
          await editDepartmentService(this.new_dept);
          this.$message.success("修改成功");
          this.getDepartment();
          this.dialogVisible = false;
        }
      });
    },
    //删除部门
    deleteDepartment(id) {
      this.$confirm("此操作将永久删除该部门, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteDepartmentService(id);
          this.getDepartment();
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
  .tree-manager-box {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    padding-left: 15px;
  }
}
</style>
